package com.me.exbean.util;

import com.lcx.annotation.Autowired;
import com.lcx.annotation.IOCValue;
import com.lcx.annotation.JsObject;
import com.lcx.core.Scanner;
import com.me.entity.MuliteFile;
import com.me.util.FileUtils;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.File;

@IOCValue
@JsObject(name = "fileUtil")
public class SelectFile {

    private FileChooser fileChooser;

    @Autowired
    private Stage stage;

    @JsObject
    public MuliteFile selectFile(String [] fileTypes){
        if(fileChooser == null){
            fileChooser = new FileChooser();
            fileChooser.setTitle("选择文件");
        }
        fileChooser.getExtensionFilters().clear();
        if(fileTypes != null && fileTypes.length > 0){
            for(String str:fileTypes){
                fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("指定文件",fileTypes));
            }
        }

        File file = fileChooser.showOpenDialog(stage);
        if(file == null) return null;
        return exchangeFile(file,null);

    }

    @JsObject
    public MuliteFile selectFileForSave(String [] fileTypes){
        if(fileChooser == null){
            fileChooser = new FileChooser();
            fileChooser.setTitle("选择文件");
        }
        fileChooser.getExtensionFilters().clear();
        if(fileTypes != null && fileTypes.length > 0){
            for(String str:fileTypes){
                fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("指定文件",fileTypes));
            }
        }
        File file = fileChooser.showSaveDialog(stage);
        if(file == null) return null;
        return exchangeFile(file,null);

    }

    @JsObject
    public String formatFileSize(long size){
        return FileUtils.formatB(size);
    }

    public static MuliteFile exchangeFile(File file,MuliteFile muliteFile){
        if(muliteFile == null) muliteFile = new MuliteFile();
        if(file.isDirectory()){
            muliteFile.setFile(false);
        }else{
            muliteFile.setAbsolutePath(file.getAbsolutePath().replaceAll("\\\\","/"));
            muliteFile.setPath(file.getPath().replaceAll("\\\\","/"));
            muliteFile.setLength(file.length());
            muliteFile.setFileName(file.getName());
        }
        return muliteFile;
    }

}
